<?php include "classes.inc" ?>
<?php include "constants.inc" ?>
<?php session_start(); ?>
<?php

	$connect = mysql_connect(DB_SERVER, DB_USER, DB_PWD);
	mysql_select_db(DB_CATALOG);

  	if (isset($_GET['match'])) {
    	$userInput = $_GET['match'];
  	}

  	if (isset($_GET['club_id'])) {
   		$clubId = $_GET['club_id'];
  	}

  	if (isset($_SESSION['dep'])) {
    	$dep = $_SESSION['dep'];
    
    	$query = "SELECT group_id from zt_group g 
			join zt_tournament t on t.tournament_id = g.tournament_id 
			where t.isCurrent = 1 and g.group_name = '".$dep."'";
	    $result = mysql_query($query, $connect);
	    $row = mysql_fetch_assoc($result);
	    $groupId = $row['group_id'];
  	}

  	if (isset($_SESSION['round'])) {
    	$round = $_SESSION['round'];
  	}

	
	if (isset($dep) && isset($round) && isset($clubId)) {
    	$result = mysql_query("select t.team_id, t.team_name 
		    from zt_calendar_pairing cp
		    join zt_calendar c on cp.calendar_id = c.calendar_id 
		    join zt_team t on t.team_id = cp.home_team
		    join zt_tournament tr on tr.tournament_id = t.tournament_id
		    join club cl on cl.club_id = t.club_id 
		    where tr.iscurrent = 1 and c.round_nr = "
    		.$round." and t.group_id = ".$groupId."
    		order by t.team_name", $connect);
  	} else {
    	$result = mysql_query("select t.team_id, t.team_name 
	    	from zt_calendar_pairing cp
		    join zt_calendar c on cp.calendar_id = c.calendar_id 
		    join zt_team t on t.team_id = cp.home_team
		    join zt_tournament tr on tr.tournament_id = t.tournament_id 
		    join club cl on cl.club_id = t.club_id
		    where tr.iscurrent = 1 order by t.team_name", $connect);
  	}

  	$resultTypeItems = array();
	while ($row = mysql_fetch_assoc($result)) {
	    if ( isset($userInput) && !empty($userInput) ) {
	      	if (substr_compare($row['team_name'], $userInput, 0, 1) === 0) {
	        	$keys[] = $row['team_id'];
	        	$values[] = $row['team_name'];
	        	$resultTypeItems = array_combine($keys, $values);
	    	}
	    } else {
	      	$keys[] = $row['team_id'];
	      	$values[] = $row['team_name'];
	      	$resultTypeItems = array_combine($keys, $values);
	    }
	}

  	echo json_encode($resultTypeItems);
?>